<template>



<div class="demo-date-picker">
  <div class="block">
  <el-date-picker
      v-model="value1"
      type="date"
      placeholder="选择日期"
      :size="size"
      @change="handleDateChange"
  />
  </div>
</div>
<br>


<h3 v-if="loading">Loading data...</h3>
<div v-else-if="error" class="error">
  <p>Error: {{ error.message }}</p>
</div>
<div v-else>
  <div v-for="(group, index) in groupedData" :key="index" class="time-group">
    
    <TenMinutesCompositeInformaion
      :time="`${group.date} ${group.interval}`"
      :count="group.items.length"
      :images="changeGroupItemsMap(group).items.map(item => item.imageUrl)"
    />
     <!-- :images="group.items.map(item => item.imageUrl)" -->
  </div>
</div>

  <!-- <TenMinutesCompositeInformaion /> -->
    <!-- <div>
    <h3 v-if="loading">Loading data...</h3>
    <div v-else-if="error" class="error">
      <p>Error: {{ error.message }}</p>
    </div>
        <div v-else>
      <div v-for="(group, index) in groupedData" :key="index" class="time-group">
        <h3>{{ group.interval }}</h3>
        <div class="image-container">
          <div v-for="(item, itemIndex) in group.items" :key="itemIndex" class="image-item">
            <img v-if="item.imageUrl" :src="item.imageUrl" :alt="item.information" class="image" />
            <p v-else>No Image Available</p>
            <p class="image-info">{{ formatDate(item.createdAt) }}</p>
          </div>
        </div>
      </div>
    </div>
     <div v-else class="image-container">
      <div v-for="(item, index) in parsedData" :key="item.informationId" class="image-item">
        <img v-if="item.imageUrl" :src="item.imageUrl" :alt="item.information" class="image" />
        <p v-else>No Image Available</p>
        <p class="image-info">{{ formatDate(item.createdAt) }}</p>
      </div>
    </div> -->
  <!-- </div> --> 

  <!-- <h3 v-if="loading">Loading data...</h3>
    <div v-else-if="error" class="error">
      <p>Error: {{ error.message }}</p>
    </div>
    <div v-else>
      <div v-for="(group, index) in groupedData" :key="index" class="time-group">
        <h3>{{ group.date }} {{ group.interval }}</h3>
        <div class="image-container">
          <div v-for="(item, itemIndex) in group.items" :key="itemIndex" class="image-item">
            <img v-if="item.imageUrl" :src="item.imageUrl" :alt="item.information" class="image" />
            <p v-else>No Image Available</p>
            <p class="image-info">{{ formatDate(item.createdAt) }}</p>
          </div>
        </div>
      </div>
    </div> -->




</template>

<script setup lang="ts">
import{convertToLocalUrl} from '../assets/js/changeURL.js'
import TenMinutesCompositeInformaion from './TenMinutesCompositeInformaion.vue'
import {getCameraInformation} from '../assets/js/getCameraInformation.js'
import { getCameraInformationByDate } from '../assets/js/getCameraInformationByDate.js';
import { groupAllDataByTimeInterval } from '../assets/js/dataGrouper.js';
import { onMounted, ref } from 'vue'

const parsedData = ref([]);
const loading = ref(true);
const error = ref(null);


const size = ref<'default' | 'large' | 'small'>('default')
const value1 = ref(null); // 初始化为 null
const groupedData = ref([]);
const date = ref(new Date());

const host = window.location.hostname; // 获取当前主机名

onMounted(async () => {
  try {
    const cameraId = 3;
    parsedData.value = await getCameraInformation(cameraId);
    groupedData.value = groupAllDataByTimeInterval(parsedData.value);
    console.log(groupedData.value);
    error.value = null;
  } catch (err) {
    error.value = err;
  } finally {
    loading.value = false;
  }


});

async function handleDateChange() {
  loading.value = true;
  try {
    if (!value1.value) {
      // 如果没有选择日期，加载默认数据
      const cameraId = 3;
      parsedData.value = await getCameraInformation(cameraId);
    } else {
      // 根据选择的日期加载数据
      const cameraId = 3;
      const formattedDate = formatDatePickerDate(value1.value);
      console.log("Formatted Date:", formattedDate);
      parsedData.value = await getCameraInformationByDate(cameraId, formattedDate);
    }
    
    error.value = null;
  } catch (err) {
    error.value = err;
  } finally {
    loading.value = false;
  }

  // 在获取数据之后进行分组
  if (!loading.value) {
    if (value1.value) {
      const selectedDate = new Date(value1.value);
      // 过滤出选定日期的数据并重新分组
      const filteredData = parsedData.value.filter(item => {
        const itemDate = new Date(item.createdAt);
        return (
          itemDate.getDate() === selectedDate.getDate() &&
          itemDate.getMonth() === selectedDate.getMonth() &&
          itemDate.getFullYear() === selectedDate.getFullYear()
        );
      });
      groupedData.value = groupAllDataByTimeInterval(filteredData);
    } else {
      groupedData.value = groupAllDataByTimeInterval(parsedData.value);
    }
  }
}


// 格式化日期选择器的日期
function formatDatePickerDate(value){
      // 解析日期字符串
    const date = new Date(Date.parse(value));
    
    // 获取年、月、日
    const year = date.getFullYear();
    let month = date.getMonth() + 1; // 月份从0开始
    const day = date.getDate();
    
    // 格式化月份为1-12的数字形式
    month = month < 10 ? month : month;
    
    // 组合成所需的格式
    return `${year}-${month}-${day}`;

}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '';
    return new Intl.DateTimeFormat('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false,
        timeZone: 'Asia/Shanghai' // 指定时区为中国标准时间
    }).format(new Date(dateString));
}

function changeGroupItemsMap(group1){
  // 替换每个组内的图片URL为本地服务器地址
  const updatedItems = group1.items.map(item => {
    return {
      ...item,
      imageUrl: convertToLocalUrl(item.imageUrl, host, 8080) // 替换为你的本地服务器地址和端口
    };
  });
  console.log("Original Items:", group1.items);
  // console.log("Updated Items:", updatedItems);
  console.log("Updated Items:", updatedItems);
  return {
    ...group1,
    items: updatedItems
  };
  // groupedData.value = groupedData.value.map(group => {
  //   return {
  //     ...group,
  //     items: group.items.map(item => {
  //       return {
  //         ...item,
  //         imageUrl: convertToLocalUrl(item.imageUrl,"localhost", 8080) // 替换为你的本地服务器地址和端口
  //       };
  //     })
  //   };
  // });
  // return groupedData;
}
</script>




<style scoped>

.time-group {
  margin-bottom: 20px;
}

.time-group h3 {
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}


.demo-date-picker {
  width: 100%;
  padding: 20px;
  z-index: 9999; /* 确保日期选择器在最上层 */

}
.block {
  position: absolute;
  top: 10;
  left: 10;
  margin-bottom: 0px;
  z-index: 9999; /* 确保日期选择器在最上层 */
}
.image-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 20px;
}

.image-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 200px;
}

.image {
  width: 100%;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.image-info {
  margin-top: 8px;
  text-align: center;
  color: #333;
}
</style>